#!/sbin/openrc-run

description="Daemon that performs least recently used (LRU) eviction of Docker images"

: ${keep:=}
: ${threshold:="10GB"}
: ${logfile="/var/log/$RC_SVCNAME.log"}
: ${statedir:="/var/lib/docuum"}
: ${command_user:="docuum:docker"}
: ${respawn_delay:=5}

command="/usr/bin/docuum"
command_args="--threshold '$threshold' $command_args"
command_background="yes"
pidfile="/run/$RC_SVCNAME.pid"
error_log="$logfile"

depend() {
	need docker
}

start_pre() {
	# docuum automatically appends '/docuum' to the path.
	export XDG_DATA_HOME="${statedir%/docuum}"

	if [ "$keep" ]; then
		command_args="$command_args $(set -f; printf "--keep '%s' " $keep)"
	fi
	if [ "$logfile" ]; then
		checkpath -f -m 640 -o "$command_user" -q "$logfile" || return 1
	fi
	checkpath -d -m 750 -o "$command_user" "$statedir"
}

stop_post() {
	# Kill orphaned processes.
	pkill -U "${command_user%:*}" -P 1 -f 'docker events'

	return 0
}
